package controls;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import main.Application;

public class Thinker extends JLabel implements MouseMotionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String path =  "D:/looser/zboon-soft/systemArchiwizacjiDoc/_repoProject/zboon_icons/ballssm";
	public static final int NUM_FRAMES = 24;
	public static final int FPS = 16;
	private int frameNumber = 0;
	private ImageIcon[] images = new ImageIcon[NUM_FRAMES];
	private int delay;	
	private String conditionalZeroStr = "0";
	
	private boolean konczPan;
	
	public Thinker (){
		super();
		delay = 1000 / FPS;
		setHorizontalAlignment(JLabel.CENTER);
		updatePicture(0);			
		setSize(20,20);
		setVisible(true);
	}
	
	public void startAnimation()
	{
		Application.getInstance().setEnableApp(false);
		this.setLocation(getLabelPos(MouseInfo.getPointerInfo().getLocation()));
		konczPan=false;
		Thread timer = new Thread() //musze zawsze tworzyc nowy!!
		{
			@Override
			public void run() {
				while(!konczPan)
				{
					try {
						sleep(delay);
					} catch (InterruptedException e) 
					{
						Application.getInstance().notifyAboutException(e);
						break;
					}
					update();
				}
			}
		};
		timer.start();
	}
	
	public void stopAnimation()
	{		
		konczPan=true;	
		Application.getInstance().setEnableApp(true);
	}
	
	//called when the timer fires
	public void update ()
	{
		if (frameNumber == (NUM_FRAMES - 1))
		{
			frameNumber = 0;
		}
		else
			frameNumber ++;
		
		updatePicture (frameNumber);				
	}

	protected void updatePicture (int frameNum)
	{
		if (images[frameNumber] == null)
		{	
			conditionalZeroStr = (((frameNumber+1) >= 10) ? "" : "0");
			images[frameNumber] = createImageIcon (path + conditionalZeroStr + (frameNumber+1) + ".png");
		}
		
		if (images[frameNumber] != null)
		{
			setIcon (images[frameNumber]);
			
			super.paintAll(super.getGraphics());
		}
		else
		{
			setText("" + conditionalZeroStr + frameNumber);
		}	
	}
	
    /** Returns an ImageIcon, or null if the path was invalid. */
    private static ImageIcon createImageIcon(String path) {
        if (path != null && path!="") {
            return new ImageIcon(path);
        } else {
            if (path == "") return null;
        	System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

	@Override
	public void mouseDragged(MouseEvent e) 
	{
		this.setLocation(getLabelPos(e.getPoint()));		
	}

	@Override
	public void mouseMoved(MouseEvent e) 
	{
		this.setLocation(getLabelPos(e.getPoint()));		
	}
	private Point getLabelPos(Point mousePos)
	{
		return new Point(mousePos.x+5,mousePos.y-15);
	}
}
